package com.xushu.springframework;

import com.xushu.app.service.AService;
import com.xushu.app.service.UserService;
import com.xushu.springframework.Autowired;
import com.xushu.springframework.BeanPostProcessor;
import com.xushu.springframework.Component;
import com.xushu.springframework.JdkDynimcProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 实现AOP的BeanPostProcessor （Spring内置提供的）
public class AutoProxyCreatorBeanPostProcessor implements BeanPostProcessor,SmartInstantiationAwareBeanPostProcessor {

    // 缓存已经创建好的aop的bean
    private final Map<String, Object> earlyBeanReferences = new ConcurrentHashMap<>(16);




    // 循环依赖中调用的，解决循环依赖的bean属性 和 容器中的bean 不一致
    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) {
        earlyBeanReferences.put(beanName, bean);
        return createProxy( bean, beanName);
    }

    public Object createProxy(Object bean, String beanName)
    {
        // 创建动态代理
        // 匹配切点表达式 ----> aspectj 能力
        if(bean instanceof AService){
            JdkDynimcProxy jdkDynimcProxy = new JdkDynimcProxy(bean);
            return jdkDynimcProxy.getProxy();
        }

        // 没有实现AOP 就返回原始bean对象
        return bean;
    }

    // 初始化后
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        // 如果没有提前创建， 就在初始化后创建
        if(!earlyBeanReferences.containsKey(beanName)) {
            return createProxy(bean, beanName);
        }
        // 如果提前已经创建， 不需再创建
        return bean;
    }
}